package com.mz361.common.utils;


import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CosUtil {
    @Autowired
    private COSClient cosClient;
    private String bucketName = "std-1327002262";
    private String tmp_bucketName = "tmp-1327002262";
    private String img_bucketName = "img-1327002262";

    public URL presignedUrl(String pdfName, String watermarkText) {

        try {
            if (StringUtil.notEmpty(watermarkText)) {
                COSObject cosObject = cosClient.getObject(new GetObjectRequest(bucketName, pdfName));
                byte[] originalPdfBytes = readPdfBytes(cosObject.getObjectContent());

                Font watermarkFont = new Font(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED),
                        30, Font.BOLD, new com.itextpdf.text.BaseColor(128, 128, 128));
                byte[] watermarkedPdfBytes = PdfWatermarkUtil.addTextWatermark(originalPdfBytes, watermarkText,
                        watermarkFont, 50, 50, 0.3f);
//
                // 生成临时文件名，避免覆盖原文件，这里使用UUID来生成唯一文件名
                String watermarkedPdfFileName = StringUtil.getAutoEntry("tmp_") + ".pdf";

                FileOutputStream fileOutputStream = new FileOutputStream(watermarkedPdfFileName);
                fileOutputStream.write(watermarkedPdfBytes);
                fileOutputStream.close();
                File file = new File(watermarkedPdfFileName);
//
//                // 将添加水印后的PDF文件上传回COS（可以考虑优化，如判断文件是否已存在等情况）
                PutObjectRequest putRequest = new PutObjectRequest(tmp_bucketName, watermarkedPdfFileName,
                        file);

                PutObjectResult putResult = cosClient.putObject(putRequest);
                file.delete();//删除本临时生成的文件
//                // 生成临时访问URL 1分钟有效
                Date expiration = new Date(System.currentTimeMillis() + 60 * 1000);
                return cosClient.generatePresignedUrl(tmp_bucketName, watermarkedPdfFileName, expiration);
            } else {
                GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, pdfName)
                        .withExpiration(DateUtils.getDayHourAfter(new Date(), 1)); // 设置过期时间
                return cosClient.generatePresignedUrl(request);
            }
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<String> imageUrls(String pdfName, Integer start, Integer end) {
        try {
            String imageFloder = pdfName.substring(0, pdfName.indexOf("."));
            List<String> imageUrls = new ArrayList<>();
            for (int i = start; i <= end; i++) {
                String imageName = imageFloder + "/page_" + i + ".png";//截图文件
                GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(img_bucketName, imageName); // 设置过期时间
                URL presignedUrl = cosClient.generatePresignedUrl(request);
                imageUrls.add(presignedUrl.toString());
            }
            return imageUrls;
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static byte[] readPdfBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384]; // 每次读取16KB，可根据实际情况调整块大小
        try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
            while ((nRead = bis.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
        }
        return buffer.toByteArray();
    }

    public static List<File> listPngFiles(File dir) {
        List<File> pngFiles = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    pngFiles.addAll(listPngFiles(file));
                } else if (file.getName().toLowerCase().endsWith(".png")) {
                    pngFiles.add(file);
                }
            }
        }
        return pngFiles;
    }

    public void uploadPngFiles(File dir) {
        List<File> pngFiles = listPngFiles(dir);
        for (File file : pngFiles) {
            String key = file.getAbsolutePath().substring(dir.getAbsolutePath().length() + 1).replace("\\", "/");
            key = "standard/files/" + key;
            PutObjectRequest putObjectRequest = new PutObjectRequest(img_bucketName, key, file);
            try {
                cosClient.putObject(putObjectRequest);
                System.out.println("成功上传文件: " + file.getAbsolutePath() + " 到腾讯云对象存储，对象键为: " + key);
            } catch (Exception e) {
                System.err.println("上传文件 " + file.getAbsolutePath() + " 出现错误: " + e.getMessage());
            }
        }
    }

    public Long getFileSize(String pdfName) {
        ObjectMetadata getObjectResult = cosClient.getObjectMetadata(bucketName, pdfName);
        return getObjectResult.getContentLength();
    }


}
